const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::city');
const nconf = require('nconf');
const router = require('koa-router')();
const jwt = require('jsonwebtoken');
const cookie = require('cookie');

const user_service = require(global.prefixPath + '/services/user');

/**
 * 用户登陆
 * 1. 验证用户账号密码
 * 2. 验证通过计算token并返回
 * 3. 前台保存token，下次请求数据时带上token
**/
router.post('/login', async (ctx, next) => {
	ctx.checkQuery('q').notEmpty("query param is missing!").isJSON("param must be a json string!");

	if (ctx.errors) {
		ctx.status = 400;
		ctx.body = {
			ok: 0,
			msg: ctx.errors
		};
		return;
	}

	let q = JSON.parse(ctx.query.q);

	try {
		var user = await user_service.checkUser(q['query']);

		if (!user) {
			ctx.body = {
				ok: 0,
				msg: '账号密码错误'
			};
			return;
		}

		console.log(user);

		let app = ctx.app;
		var token = jwt.sign({
			exp: Math.floor(Date.now() / 1000) + parseInt(nconf.get('jwt').expiretime),
			name: user.username
		}, app.secret);

		console.log(token);

		// cookie中也种上token，方便页面后台渲染时就可以获取登陆状态，避免由ajax再次获取会刷新页面
		ctx.res.setHeader('set-cookie', cookie.serialize('access_token', token, {
	      httpOnly: true,
	      maxAge: parseInt(nconf.get('jwt').expiretime)
	    }));
		ctx.body = {
			ok: 1,
			token: token
		};
	} catch (err) {
		console.error(err);
		throw err;
	}

});

// ajax获取已登陆用户信息，前置token验证
router.get('/loginuser', async (ctx, next) => {
	try {
		if (ctx.decoded) {
			console.log(ctx.decoded);
			ctx.body = {
				ok: 1,
				user: ctx.decoded
			};
		}
		else {
			ctx.body = {
				ok: 0,
				msg: '用户未登陆'
			};
		}
	}
	catch (err) {
		console.error(err);
	}
});

// 用户登出，清空cookie
router.get('/logoutuser', async (ctx, next) => {
	try {
		ctx.res.setHeader('set-cookie', cookie.serialize('access_token', '', {
	      httpOnly: true,
	      maxAge: -1
	    }));
		ctx.body = {
			ok: 1
		};
	}
	catch (err) {
		ctx.body = {
			ok: 0,
			msg: err
		};
	}

});


exports = module.exports = router;